/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
limitations under the License.*/

package zuo.biao.library.util;

import ohos.app.Context;
import ohos.app.Environment;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.data.usage.DataUsage;
import ohos.data.usage.MountState;

import java.io.*;
import java.util.Locale;

/**
 * 数据存储工具类
 * <br> 1.将fileRootPath中的包名（这里是zblibrary.demo）改为你的应用包名
 * <br> 2.在Application中调用init方法
 */
public class DataKeeper {
    private static final String TAG = "DataKeeper";

    private static final String SAVE_SUCCEED = "保存成功";
    private static final String SAVE_FAILED = "保存失败";
    private static final String DELETE_SUCCEED = "删除成功";
    private static final String DELETE_FAILED = "删除失败";

    /**
     * 默认ROOT_SHARE_PREFS_
     */
    public static final String ROOT_SHARE_PREFS_ = "DEMO_SHARE_PREFS_";

    // 文件缓存<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    /**
     * 必须将fileRootPath中的包名（这里是zblibrary.demo）改为你的应用包名
     */
    public static String fileRootPath = null;

    private static  String accountPath = fileRootPath + "account/";
    private static  String audioPath = fileRootPath + "audio/";
    private static  String videoPath = fileRootPath + "video/";
    private static  String imagePath = fileRootPath + "image/";
    private static  String tempPath = fileRootPath + "temp/";
    // 文件缓存>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    // 存储文件的类型<<<<<<<<<<<<<<<<<<<<<<<<<
    private static final int TYPE_FILE_TEMP = 0; // 保存保存临时文件
    private static final int TYPE_FILE_IMAGE = 1; // 保存图片
    private static final int TYPE_FILE_VIDEO = 2; // 保存视频
    private static final int TYPE_FILE_AUDIO = 3; // 保存语音

    // 存储文件的类型>>>>>>>>>>>>>>>>>>>>>>>>>

    // 不能实例化
    private DataKeeper() {
    }

    private static Context context;

    /**
     * 获取context，获取存档数据库引用
     * @param context_ context_
     */
    public static void init(Context context_) {
        context = context_;
        fileRootPath = getSDPath(context_) != null ? (getSDPath(context_) + "/zblibrary.demo/") : null;
        Log.info(TAG, "init fileRootPath = " + fileRootPath);
        // 判断SD卡存在
        if (DataUsage.getDiskMountedStatus() == MountState.DISK_MOUNTED) {
            if (fileRootPath != null) {
                File file = new File(imagePath);
                if (!file.exists()) {
                    boolean ismk = file.mkdirs();
                }
                file = new File(videoPath);
                if (!file.exists()) {
                    boolean ismk = file.mkdir();
                }
                file = new File(audioPath);
                if (!file.exists()) {
                    boolean ismk = file.mkdir();
                }
                file = new File(fileRootPath + accountPath);
                if (!file.exists()) {
                    boolean ismk = file.mkdir();
                }
                file = new File(tempPath);
                if (!file.exists()) {
                    boolean ismk = file.mkdir();
                }
            }
        }
    }

    /**
     * 获取轻量存储实例
     *
     * @return Preferences
     */
    public static Preferences getRootSharedPreferences() {
        return new DatabaseHelper(context).getPreferences(ROOT_SHARE_PREFS_);
    }

    // **********外部存储缓存***************

    /**
     * 存储缓存文件 返回文件绝对路径
     *
     * @param file 要存储的文件
     * @param type 文件的类型
     *             IMAGE = "imgae";							//图片
     *             VIDEO = "video";							//视频
     *             VOICE = "voice";							//语音
     *             = "voice";							//语音
     * @return 存储文件的绝对路径名
     */
    public static String storeFile(File file, String type) {
        if (!hasSDCard()) {
            return null;
        }
        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        byte[] data = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data, 0, data.length);
            in.close();
        } catch (IOException e) {
            Log.error(
                    TAG,
                    "storeFile  try { FileInputStream in = new FileInputStream(file); ... >>"
                            + " } catch (IOException e) {"
                            + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    Log.error("IOException", e.getMessage());
                }
            }
        }
        return storeFile(data, suffix, type);
    }

    /**
     * 若SDCard不存在返回null
     *
     * @param data   data
     * @param suffix suffix
     * @param type   type
     * @return 存储文件的绝对路径名
     */
    public static String storeFile(byte[] data, String suffix, String type) {
        if (!hasSDCard()) {
            return null;
        }
        String path = null;
        if (type.equals(TYPE_FILE_IMAGE)) {
            path =
                    imagePath
                            + "IMG_"
                            + Long.toHexString(System.currentTimeMillis()).toUpperCase((Locale.ROOT))
                            + "."
                            + suffix;
        } else if (type.equals(TYPE_FILE_VIDEO)) {
            path =
                    videoPath
                            + "VIDEO_"
                            + Long.toHexString(System.currentTimeMillis()).toUpperCase((Locale.ROOT))
                            + "."
                            + suffix;
        } else if (type.equals(TYPE_FILE_AUDIO)) {
            path =
                    audioPath
                            + "VOICE_"
                            + Long.toHexString(System.currentTimeMillis()).toUpperCase((Locale.ROOT))
                            + "."
                            + suffix;
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            out.write(data, 0, data.length);
            out.close();
        } catch (FileNotFoundException e) {
            Log.error(
                    TAG,
                    "storeFile  try { FileInputStream in = new FileInputStream(file); ... >>"
                            + " } catch (FileNotFoundException e) n"
                            + e.getMessage()
                            + "\n\n >> path = null;");
            path = null;
        } catch (IOException e) {
            Log.error(
                    TAG,
                    "storeFile  try { FileInputStream in = new FileInputStream(file); ... >>"
                            + " } catch (IOException e) {"
                            + e.getMessage()
                            + "\n\n >> path = null;");
            path = null;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    Log.error("IOException", e.getMessage());
                }
            }
        }
        return path;
    }

    /**
     * jpg
     *
     * @param fileName fileName
     * @return String
     */
    public static String getImageFileCachePath(String fileName) {
        return getFileCachePath(TYPE_FILE_IMAGE, fileName, "jpg");
    }

    /**
     * mp4
     *
     * @param fileName fileName
     * @return String
     */
    public static String getVideoFileCachePath(String fileName) {
        return getFileCachePath(TYPE_FILE_VIDEO, fileName, "mp4");
    }

    /**
     * mp3
     *
     * @param fileName fileName
     * @return String
     */
    public static String getAudioFileCachePath(String fileName) {
        return getFileCachePath(TYPE_FILE_AUDIO, fileName, "mp3");
    }

    /**
     * 获取一个文件缓存的路径
     * @param fileType fileTypefileType
     * @param fileName fileName
     * @param formSuffix formSuffix
     * @return str
     */
    public static String getFileCachePath(int fileType, String fileName, String formSuffix) {
        switch (fileType) {
            case TYPE_FILE_IMAGE:
                return imagePath + fileName + "." + formSuffix;
            case TYPE_FILE_VIDEO:
                return videoPath + fileName + "." + formSuffix;
            case TYPE_FILE_AUDIO:
                return audioPath + fileName + "." + formSuffix;
            default:
                return tempPath + fileName + "." + formSuffix;
        }
    }

    /**
     * null若存在SD 则获取SD卡的路径 不存在则返回
     * @param context context
     * @return str
     * */
    public static String getSDPath(Context context) {
        String path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        return path;
    }

    /**
     * 判断是否有SD卡
     * @return boolean
     */
    public static boolean hasSDCard() {
        return DataUsage.getDiskMountedStatus() == MountState.DISK_MOUNTED;
    }

    // 使用SharedPreferences保存 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 使用SharedPreferences保存
     *
     * @param path path
     * @param key key
     * @param value value
     */
    public static void save(String path, String key, String value) {
        save(path, Context.MODE_PRIVATE, key, value);
    }

    /**
     * 使用SharedPreferences保存
     *
     * @param path path
     * @param mode mode
     * @param key key
     * @param value value
     */
    public static void save(String path, int mode, String key, String value) {
        save(new DatabaseHelper(context).getPreferences(path), key, value);
    }

    /**
     * 使用SharedPreferences保存
     *
     * @param sdf sdf
     * @param key key
     * @param value value
     */
    public static void save(Preferences sdf, String key, String value) {
        if (sdf == null || StringUtil.isNotEmpty(key, false) == false || StringUtil.isNotEmpty(value, false) == false) {
            Log.error(TAG, "save sdf == null || \n key = " + key + ";\n value = " + value + "\n >> return;");
            return;
        }
        sdf.delete(key).putString(key, value).flushSync();
    }

    // 使用SharedPreferences保存 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}
